//
//  ViewController.m
//  UITextField
//
//  Created by Hello Cai on 2021/5/21.
//

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>

@property(nonatomic, strong)UITextField *textField;
@property(nonatomic, strong)UIDatePicker *datePicker;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTextField];
}

- (void)createTextField{
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(50,300,self.view.bounds.size.width-100,50)];
    _textField.delegate = self;
    _textField.font = [UIFont systemFontOfSize:18];
    _textField.adjustsFontSizeToFitWidth =YES;
    _textField.placeholder =@"此处应有挑选";
    _textField.borderStyle =UITextBorderStyleRoundedRect;
    //清除模式
    _textField.clearButtonMode =UITextFieldViewModeWhileEditing;
    //创建DatePicker
    _datePicker = [[UIDatePicker alloc]init];
   
    //挑选显示日期的模式
    _datePicker.datePickerMode = UIDatePickerModeDate;
    if (@available(iOS 13.4, *)) {
        //新系统日期选择器效果不同，设置成依旧使用滚轮效果
        _datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
    }
   
    //设置语言：中文
    _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    //添加事件
    [_datePicker addTarget:self action:@selector(changeValue)forControlEvents:UIControlEventValueChanged];
    //主键盘
    _textField.inputView =_datePicker;
    [self.view addSubview:_textField];
}
- (void)changeValue{
   
    //获取挑选的日期
    NSDate *date =_datePicker.date;
    NSDateFormatter *dateForm = [[NSDateFormatter alloc]init];
    //设定转换格式
//    dateForm.dateFormat =@"yyy年MM月dd日h时mm分";
    dateForm.dateFormat =@"yyy年MM月dd日";
   
    //由当前获取的NSDate数据，转换为日期字符串，显示在私有成员变量_textField上
    _textField.text = [dateForm stringFromDate:date];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     [_textField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate
//开始编辑即获取当前日期
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
     [self changeValue];
}
@end
